package com.corgi.formatter;

import com.corgi.formatter.util.ProtoBufUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @title: ProtoBufFormatter
 * @description:
 * @author: dengmiao
 * @create: 2019-11-07 11:11
 **/
@Slf4j
public class ProtoBufFormatter<T> implements Formatter<T, byte[]> {

    @Override
    public byte[] format(T o) {
        Class<T> clazz = (Class<T>) o.getClass();
        return ProtoBufUtil.serializer(o, clazz);
    }

    @Override
    public T parse(byte[] serialized, Class<T> clazz) {
        return ProtoBufUtil.deserializer(serialized, clazz);
    }

    /**
     * 合并byte数组
     * @param values
     * @return
     */
    public static byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }
}
